package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    //1. 注入es的核心客户端对象
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {

        if(null == dto){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //3. 根据idea的提示创建请求对象 并设置操作的索引
        SearchRequest requset = new SearchRequest("app_info_article");

        //4. 根据参数添加对应的查询条件 如果是多个查询 需要用boolquery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(StringUtils.isNotEmpty(dto.getSearchWords())){
            boolQuery.must(QueryBuilders.multiMatchQuery(dto.getSearchWords(), "title", "content"));

            //异步的调用方法实现搜索关键词的新增和修改
            ApUser user = AppThreadLocalUtil.getUser();
            if(null != user && dto.getFromIndex() == 0){
                apUserSearchService.insert(dto.getSearchWords(),user.getId());
            }
        }

        if(null != dto.getMinBehotTime()){
            boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        }

        requset.source().query(boolQuery);

        //5. 设置分页参数
        requset.source().from(dto.getFromIndex()).size(dto.getPageSize());

        //6. 设置排序规则
        requset.source().sort("publishTime", SortOrder.DESC);

        //7. 设置高亮显示的规则
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");

        requset.source().highlighter(highlightBuilder);

        //2. 通过核心对象调用搜索的方法
        SearchResponse response = client.search(requset, RequestOptions.DEFAULT);

        //8. 解析结果并返回
        SearchHits searchHits = response.getHits();

        SearchHit[] hits = searchHits.getHits();
        List<Map> list = new ArrayList<>(hits.length);

        for (SearchHit hit : hits) {
            Map map = JSON.parseObject(hit.getSourceAsString(), Map.class);

            //解析高亮的结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields(); //得到当前文档中所有的高亮结果
            HighlightField highlightField = highlightFields.get("title"); // 获取title字段上的高亮结果
            if(null != highlightField){
                //title字段上有高亮的结果
                String _title = highlightField.getFragments()[0].toString();
                map.put("h_title", _title); //名字前端已经写死了 所以必须要用这个名字来显示标题
            }else{
                map.put("h_title", map.get("title"));
            }

            list.add(map);
        }


        return ResponseResult.okResult(list);
    }
}
